package com.ztz.mynewdemo.fragment;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.headerfooter.songhang.library.SmartRecyclerAdapter;
import com.ztz.mynewdemo.R;
import com.ztz.mynewdemo.activity.CarouselActivity;
import com.ztz.mynewdemo.adapter.BannerAdapter;
import com.ztz.mynewdemo.adapter.DetailAdapter;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by wqewqe on 2017/12/19.
 */

public class JianShuFragment extends Fragment {
    private static final String TAG = "JianShuFragment";
    ArrayList<String> cariousWeb = new ArrayList<>();
    ArrayList<String> cariousImgs = new ArrayList<>();
    ArrayList<String> images = new ArrayList<>();
    ArrayList<String> headPortrait = new ArrayList<>();
    ArrayList<String> titles = new ArrayList<>();
    ArrayList<String> author = new ArrayList<>();
    ArrayList<String> contents = new ArrayList<>();
    @BindView(R.id.rl)
    RecyclerView rl;
    @BindView(R.id.top)
    FloatingActionButton top;
    Unbinder unbinder;
    ViewPager vp;
    BannerAdapter bannerAdapter;
    DetailAdapter detailAdapter;
    private ScheduledExecutorService scheduledExecutorService;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    parseData();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        bannerAdapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_jianshu, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        rl.setLayoutManager(new LinearLayoutManager(getActivity()));
        detailAdapter = new DetailAdapter(getContext(), images, headPortrait, titles, author, contents);
        SmartRecyclerAdapter smartRecyclerAdapter = new SmartRecyclerAdapter(detailAdapter);
        View headView = LayoutInflater.from(getContext()).inflate(R.layout.layout_headview, null);
        vp =(ViewPager)headView.findViewById(R.id.vp_head);
        bannerAdapter=new BannerAdapter(cariousImgs,getContext());
        vp.setAdapter(bannerAdapter);
        smartRecyclerAdapter.setHeaderView(headView);
        rl.setAdapter(smartRecyclerAdapter);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state)
                {
                    case 1:
                        stop();
                        break;
                    case 2:
                        if(scheduledExecutorService==null)
                        {
                            run();
                        }
                        break;
                }
            }

        });
        bannerAdapter.setCariousShow(new BannerAdapter.CariousShow() {
            @Override
            public void showView(int position) {
                Intent intent=new Intent(getActivity(), CarouselActivity.class);
                intent.putExtra(CarouselActivity.WEB_VIEW,cariousWeb);
                getActivity().startActivity(intent);
            }
        });
    }
    public void run()
    {
        scheduledExecutorService= Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(new ViewTask(),2,2, TimeUnit.SECONDS);
    }
    int currentItem=0;
    class ViewTask implements Runnable
    {
        @Override
        public void run() {
            currentItem=(currentItem+1)%cariousImgs.size();
            handler.sendEmptyMessage(0);
        }
    }
    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            vp.setCurrentItem(currentItem);
        }
    };
    public void stop()
    {
        if (scheduledExecutorService!=null)
        {
            scheduledExecutorService.shutdown();
            scheduledExecutorService=null;
        }
    }
    public void parseData() throws IOException {
        Document document = Jsoup.connect("http://www.jianshu.com/").get();
        Log.i(TAG, "parseData: " + document.title());
        Elements carousel = document.getElementsByClass("carousel-inner");
        Log.i(TAG, "parseData: " + carousel);
        for (Element slide : carousel) {
            Elements items = slide.getElementsByClass("item");
            Log.i(TAG, "parseData: " + items);
            for (Element item : items) {
                Element a = item.getElementsByTag("a").first();
                Element a1 = a.after("a");
                System.out.println("轮播图网站连接:" + a1.attr("href"));
                cariousWeb.add(a1.attr("href"));
                Element image = item.getElementsByTag("img").first();
                Element img = image.after("img");
                System.out.println("轮播图图片连接:" + img.attr("src"));
                cariousImgs.add(img.attr("src"));
            }
        }
        Elements note_list = document.getElementsByClass("note-list");
        for (Element note : note_list) {
            Elements have_img = note.getElementsByClass("have-img");
            for (Element warp : have_img) {
                Elements warp_img = warp.getElementsByClass("wrap-img");
                for (Element imgs : warp_img) {
                    Element img = imgs.getElementsByTag("img").first();
                    Element img1 = img.after("img");
                    System.out.println("图片连接" + Uri.parse(img1.attr("src")));
                    images.add(img1.attr("src"));
                }
                Elements content = warp.getElementsByClass("content");
                for (Element e : content) {
                    Element imgAuthor = e.getElementsByTag("img").first();
                    Element imgA = imgAuthor.after("img");
                    System.out.println("头像连接" + Uri.parse(imgA.attr("src")));
                    headPortrait.add(imgA.attr("src"));
                    Element nickName = e.getElementsByClass("nickname").first();
                    Element a = nickName.after("a");
                    System.out.println("作者名字" + a.text());
                    author.add(a.text());
                    Element title = e.getElementsByClass("title").first();
                    Element titleUri = title.after("a");
                    System.out.println("标题链接" + Uri.parse("http://www.jianshu.com")+ titleUri.attr("href"));
                    System.out.println("标题" + titleUri.text());
                    titles.add(titleUri.text());
                    Element p = e.getElementsByTag("p").first();
                    Element p1 = p.after("p");
                    System.out.println("内容" + p1.text());
                    contents.add(p1.text());
                }

            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.top)
    public void onViewClicked() {
        rl.smoothScrollToPosition(0);
    }
}
